package com.sunny.ihealth.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.john.waveview.WaveView;
import com.sunny.ihealth.BaseFragment;
import com.sunny.ihealth.R;
import com.sunny.ihealth.data.LocalData;
import com.sunny.ihealth.entity.app.SportData;
import com.sunny.ihealth.entity.app.UserConfig;
import com.sunny.ihealth.entity.eventbus.SportDataChangeEvent;
import com.sunny.ihealth.entity.eventbus.UserChangeEvent;
import com.sunny.ihealth.ui.activity.MainActivity;
import com.sunny.ihealth.ui.activity.PublishPostActivity;
import com.sunny.ihealth.ui.activity.StartRunActivity;
import com.sunny.ihealth.ui.view.WheelDialog;
import com.sunny.ihealth.utils.NetworkUtils;
import com.sunny.ihealth.utils.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;


public class TabMeFragment extends BaseFragment implements View.OnClickListener, WheelDialog.OnPressOKListener {

    private static final String TAG = "TAG::TabMeFragment";

    private UserConfig userConfig;
    private SportData sportData;
    private int stepCache = 0;

    private LinearLayout llWalk, llRun, llSleep;
    private TextView tvWalk, tvRun, tvSleep;
    private WaveView wvWalk, wvRun, wvSleep;
    private Button btnShare, btnRun;

    private Handler handler;

    private boolean first = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);

        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab_me, container, false);
        initViews(view);
        return view;
    }

    @Override
    public void initViews(View v) {
        wvWalk = (WaveView) v.findViewById(R.id.waveView_walk);
        wvRun = (WaveView) v.findViewById(R.id.waveView_run);
        wvSleep = (WaveView) v.findViewById(R.id.waveView_sleep);
        btnShare = (Button) v.findViewById(R.id.btn_me_share);
        btnRun = (Button) v.findViewById(R.id.btn_me_run);
        llWalk = (LinearLayout) v.findViewById(R.id.ll_me_walk);
        llRun = (LinearLayout) v.findViewById(R.id.ll_me_run);
        llSleep = (LinearLayout) v.findViewById(R.id.ll_me_sleep);
        tvWalk = (TextView) v.findViewById(R.id.tv_me_walk);
        tvRun = (TextView) v.findViewById(R.id.tv_me_run);
        tvSleep = (TextView) v.findViewById(R.id.tv_me_sleep);


        btnShare.setOnClickListener(this);
        btnRun.setOnClickListener(this);
        llWalk.setOnClickListener(this);
        llRun.setOnClickListener(this);
        llSleep.setOnClickListener(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //获取data
        MainActivity mainActivity = (MainActivity) getActivity();
        if (mainActivity != null) {
            mainActivity.initData();
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_me_share:
                if (!NetworkUtils.isNetworkAvailable(getActivity(), true)) {
                    return;
                }
                startActivity(new Intent(getActivity(), PublishPostActivity.class));
                break;
            case R.id.btn_me_run:
                if (!NetworkUtils.isNetworkAvailable(getActivity(), true)) {
                    return;
                }
                startActivity(new Intent(getActivity(), StartRunActivity.class));
                break;
            case R.id.ll_me_walk:
                WheelDialog.getWheelDialog(getContext(), WheelDialog.WheelType.WALK, WheelDialog.RunType.NONE, new float[]{userConfig.getWalk()}, this).show();
                break;
            case R.id.ll_me_run:
                WheelDialog.RunType runType;
                float[] value = new float[]{userConfig.getRunDistance() / 1000F, userConfig.getRunTime()};
                if (userConfig.getRunType() == UserConfig.TYPE_DISTANCE) {
                    runType = WheelDialog.RunType.DISTANCE;
                } else {
                    runType = WheelDialog.RunType.TIME;
                }

                WheelDialog.getWheelDialog(getContext(), WheelDialog.WheelType.RUN, runType, value, this).show();
                break;
            case R.id.ll_me_sleep:
                WheelDialog.getWheelDialog(getContext(), WheelDialog.WheelType.SLEEP, WheelDialog.RunType.NONE, new float[]{userConfig.getSleepTime()}, this).show();
                break;
        }
    }


    /**
     * 更新今日状态
     */
    private void updateCardView() {
        if (userConfig == null || sportData == null) {
            Log.e(TAG, "userConfig or sportData is null");
            return;
        }
        final int walk, runTime, runDistance, sleepTime;
        walk = sportData.getWalk() + stepCache;
        runTime = sportData.getRunTime();
        runDistance = sportData.getRunDistance();
        sleepTime = sportData.getSleepTime();
        final int pWalk = (int) (100F * walk / userConfig.getWalk());
        final int pRun;
        if (userConfig.getRunType() == UserConfig.TYPE_DISTANCE) {
            pRun = (int) (100F * runDistance / userConfig.getRunDistance());
        } else {
            pRun = (int) (100F * runTime / userConfig.getRunTime());
        }
        final int pSleep = (int) (100F * sleepTime / userConfig.getSleepTime());

        //设置百分比
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (first) {
                    first = false;
                    //显示WaveView动画
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            wvWalk.setProgressWithAnim(pWalk);
                            wvRun.setProgressWithAnim(pRun);
                            wvSleep.setProgressWithAnim(pSleep);
                        }
                    }, 500);
                } else {
                    wvWalk.setProgress(pWalk);
                    wvRun.setProgress(pRun);
                    wvSleep.setProgress(pSleep);
                }

                //设置当前值
                tvWalk.setText(walk + "步");
                if (userConfig.getRunType() == UserConfig.TYPE_DISTANCE) {
                    DecimalFormat df = new DecimalFormat("0.##");
                    tvRun.setText(df.format(runDistance / 1000F) + "公里");
                } else {
                    tvRun.setText(runTime + "分钟");
                }
                tvSleep.setText(TimeUtils.getHM(sleepTime));
            }
        });
    }


    /**
     * WheelDialog 选择完的回调
     */
    @Override
    public void done(WheelDialog.WheelType wheelType, WheelDialog.RunType runType, float number) {
        switch (wheelType) {
            case WALK:
                userConfig.setWalk((int) number);
                break;
            case RUN:
                if (runType == WheelDialog.RunType.DISTANCE) {
                    userConfig.setRunType(UserConfig.TYPE_DISTANCE);
                    userConfig.setRunDistance((int) (number * 1000));
                } else {
                    userConfig.setRunType(UserConfig.TYPE_TIME);
                    userConfig.setRunTime((int) number);
                }
                break;
            case SLEEP:
                userConfig.setSleepTime((int) number);
                break;
        }
        LocalData.setUserConfig(userConfig);
        updateCardView();
    }


    /**
     * 监听用户状态改变
     */
    @Subscribe
    public void onUserChanged(UserChangeEvent event) {
        userConfig = LocalData.getUserConfig(getCurrentUser());
        sportData = LocalData.getTodaySportData(getCurrentUser());
        stepCache = 0;
        updateCardView();
    }


    /**
     * 运动数据改变
     */
    @Subscribe
    public void onSportDataChanged(SportDataChangeEvent event) {
        if (event.getType() == SportDataChangeEvent.Type.WALK) {
            stepCache = event.getStepCache();
            if (stepCache == 0) {
                sportData = LocalData.getTodaySportData(getCurrentUser());
            }
        } else {
            sportData = LocalData.getTodaySportData(getCurrentUser());
        }
        updateCardView();
    }
}
